package com.bawei.module_mine.zhibo

import android.content.Context
import android.util.Log
import android.view.Gravity
import android.widget.Toast
import com.bawei.module_mine.model.entity.*
import com.bawei.module_mine.websocket.WebSocketUtils
import com.google.gson.Gson
import kotlinx.coroutines.*
import kotlin.random.Random

/**
 * 红包管理器
 * 负责红包的发送、接收、显示和动画效果
 */
class RedPacketManager(
    private val context: Context,
    private val webSocketUtils: WebSocketUtils,
    private val liveRoomId: String,
    private val userId: String,
    private val userName: String
) {
    
    private val gson = Gson()
    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private val activeRedPackets = mutableMapOf<String, RedPacketEntity>()
    private val redPacketCallbacks = mutableListOf<RedPacketCallback>()
    
    companion object {
        private const val TAG = "RedPacketManager"
        private const val RED_PACKET_EXPIRE_TIME = 24 * 60 * 60 * 1000L // 24小时
    }
    
    /**
     * 发送红包
     */
    fun sendRedPacket(amount: Double, count: Int, message: String) {
        val redPacketId = generateRedPacketId()
        val redPacket = RedPacketEntity(
            id = redPacketId,
            senderId = userId,
            senderName = userName,
            senderAvatar = "", // TODO: 获取用户头像
            amount = amount,
            count = count,
            remainingCount = count,
            remainingAmount = amount,
            message = message,
            createTime = System.currentTimeMillis(),
            expireTime = System.currentTimeMillis() + RED_PACKET_EXPIRE_TIME,
            status = RedPacketStatus.ACTIVE
        )
        
        // 保存到本地
        activeRedPackets[redPacketId] = redPacket
        
        // 发送WebSocket消息
        val wsMessage = WebSocketMessage(
            type = WebSocketMessageType.RED_PACKET_SEND,
            data = redPacket
        )
        
        webSocketUtils.sendMsg(gson.toJson(wsMessage))
        
        // 显示发送成功动画
        showSendRedPacketAnimation(redPacket)
        
        // 设置过期定时器
        scope.launch {
            delay(RED_PACKET_EXPIRE_TIME)
            expireRedPacket(redPacketId)
        }
        
        Log.i(TAG, "发送红包: $redPacketId, 金额: $amount, 个数: $count")
    }
    
    /**
     * 抢红包
     */
    fun grabRedPacket(redPacketId: String) {
        val redPacket = activeRedPackets[redPacketId] ?: return
        
        if (redPacket.status != RedPacketStatus.ACTIVE) {
            Toast.makeText(context, "红包已被抢完或已过期", Toast.LENGTH_SHORT).show()
            return
        }
        
        // 检查是否已经抢过
        if (redPacket.grabbers.any { it.userId == userId }) {
            Toast.makeText(context, "您已经抢过这个红包了", Toast.LENGTH_SHORT).show()
            return
        }
        
        // 发送抢红包请求
        val grabRequest = GrabRedPacketRequest(redPacketId, userId)
        val grabMessage = WebSocketMessage(
            type = WebSocketMessageType.RED_PACKET_GRAB,
            data = grabRequest
        )
        
        webSocketUtils.sendMsg(gson.toJson(grabMessage))
        
        Log.i(TAG, "抢红包: $redPacketId")
    }
    
    /**
     * 处理收到的红包消息
     */
    fun handleRedPacketMessage(message: String) {
        try {
            val webSocketMessage = gson.fromJson(message, WebSocketMessage::class.java)
            
            when (webSocketMessage.type) {
                WebSocketMessageType.RED_PACKET_SEND -> {
                    val redPacket = gson.fromJson(
                        gson.toJson(webSocketMessage.data), 
                        RedPacketEntity::class.java
                    )
                    handleNewRedPacket(redPacket)
                }
                WebSocketMessageType.RED_PACKET_GRAB -> {
                    val response = gson.fromJson(
                        gson.toJson(webSocketMessage.data), 
                        GrabRedPacketResponse::class.java
                    )
                    handleGrabRedPacketResponse(response)
                }
                WebSocketMessageType.RED_PACKET_EXPIRE -> {
                    val redPacketId = webSocketMessage.data as String
                    expireRedPacket(redPacketId)
                }
                else -> {
                    Log.d(TAG, "未处理的消息类型: ${webSocketMessage.type}")
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "处理红包消息失败", e)
        }
    }
    
    /**
     * 处理新红包
     */
    private fun handleNewRedPacket(redPacket: RedPacketEntity) {
        // 如果不是自己发送的，显示红包通知
        if (redPacket.senderId != userId) {
            showRedPacketNotification(redPacket)
        }
        
        // 通知回调
        redPacketCallbacks.forEach { it.onNewRedPacket(redPacket) }
    }
    
    /**
     * 处理抢红包响应
     */
    private fun handleGrabRedPacketResponse(response: GrabRedPacketResponse) {
        if (response.success) {
            showGrabSuccessAnimation(response.amount ?: 0.0, response.isBestLuck)
            Toast.makeText(context, "恭喜抢到 ${response.amount} 元！", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(context, response.message, Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 红包过期
     */
    private fun expireRedPacket(redPacketId: String) {
        val redPacket = activeRedPackets[redPacketId] ?: return
        // 创建新的红包对象，更新状态
        val expiredRedPacket = redPacket.copy(status = RedPacketStatus.EXPIRED)
        activeRedPackets.remove(redPacketId)
        
        // 通知回调
        redPacketCallbacks.forEach { it.onRedPacketExpired(expiredRedPacket) }
        
        Log.i(TAG, "红包过期: $redPacketId")
    }
    
    /**
     * 显示发送红包动画
     */
    private fun showSendRedPacketAnimation(redPacket: RedPacketEntity) {
        scope.launch {
            val toast = Toast.makeText(context, "红包发送成功！", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        }
    }
    
    /**
     * 显示红包通知
     */
    private fun showRedPacketNotification(redPacket: RedPacketEntity) {
        scope.launch {
            val toast = Toast.makeText(
                context, 
                "${redPacket.senderName} 发送了一个红包", 
                Toast.LENGTH_SHORT
            )
            toast.setGravity(Gravity.TOP or Gravity.CENTER_HORIZONTAL, 0, 100)
            toast.show()
        }
    }
    
    /**
     * 显示抢红包成功动画
     */
    private fun showGrabSuccessAnimation(amount: Double, isBestLuck: Boolean) {
        scope.launch {
            val message = if (isBestLuck) {
                "手气最佳！抢到 $amount 元"
            } else {
                "抢到 $amount 元"
            }
            
            val toast = Toast.makeText(context, message, Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        }
    }
    
    /**
     * 生成红包ID
     */
    private fun generateRedPacketId(): String {
        return "rp_${System.currentTimeMillis()}_${Random.nextInt(1000, 9999)}"
    }
    
    /**
     * 添加回调
     */
    fun addCallback(callback: RedPacketCallback) {
        redPacketCallbacks.add(callback)
    }
    
    /**
     * 移除回调
     */
    fun removeCallback(callback: RedPacketCallback) {
        redPacketCallbacks.remove(callback)
    }
    
    /**
     * 获取活跃红包列表
     */
    fun getActiveRedPackets(): List<RedPacketEntity> {
        return activeRedPackets.values.filter { it.status == RedPacketStatus.ACTIVE }
    }
    
    /**
     * 清理资源
     */
    fun destroy() {
        scope.cancel()
        redPacketCallbacks.clear()
        activeRedPackets.clear()
    }
    
    /**
     * 红包回调接口
     */
    interface RedPacketCallback {
        fun onNewRedPacket(redPacket: RedPacketEntity)
        fun onRedPacketExpired(redPacket: RedPacketEntity)
        fun onRedPacketGrabbed(redPacket: RedPacketEntity, grabber: RedPacketGrabber)
    }
} 